import { mountReactApp } from "./ReactRoot";
import { setupMessageHandlers } from "./Messaging";
import { setupPageObserver } from "./DomObserver";
import { MessageSender } from "@utils/messaging";
import { MessageType, type CountElementsRequest } from "@utils/types";
import { CONTENT_SCRIPT_MATCHES, DEBUG, SELECTORS, STORAGE_KEYS } from "@utils/constants";
import { hydrateAppState } from "@content/state/appState";

export async function initializeExtension() {
  // 避免重复初始化
  if (document.getElementById("wxt-floating-button")) {
    console.log("ℹ️ Content script already initialized");
    return;
  }

  // React 挂载
  const components = mountReactApp();

  // 初始化响应式全局状态（Valtio）
  await hydrateAppState();

  // plus 按钮
  // 初始注入一次，后续由 DOM 观察器增量注入
  import("../components/PlusButtons").then((m) => m.injectPlusButtons(document));

  // 消息监听
  setupMessageHandlers(components);

  // DOM 观察
  setupPageObserver();

  // 与 background 通信（示例：保存页面统计）
  communicateWithBackground();

  if (DEBUG) {
    console.log("✅ Content Script initialized successfully");
  }
}

export async function communicateWithBackground() {
  try {
    const tabResponse = await MessageSender.sendToBackground({
      type: MessageType.GET_TAB_INFO,
    } as any);

    if (DEBUG) {
      console.log("📋 Tab info from background:", tabResponse);
    }

    const pageData = {
      url: window.location.href,
      title: document.title,
      timestamp: Date.now(),
      userAgent: navigator.userAgent,
      viewport: {
        width: window.innerWidth,
        height: window.innerHeight,
      },
      pageStats: {
        links: document.querySelectorAll(SELECTORS.LINKS).length,
        images: document.querySelectorAll(SELECTORS.IMAGES).length,
        forms: document.querySelectorAll(SELECTORS.FORMS).length,
      },
    };

    await MessageSender.sendToBackground({
      type: MessageType.SAVE_DATA,
      key: STORAGE_KEYS.USER_DATA,
      data: pageData,
    } as any);

    if (DEBUG) {
      console.log("💾 Page data saved to background");
    }
  } catch (error) {
    console.error("❌ Failed to communicate with background:", error);
  }
}

export function checkPageCompatibility(): boolean {
  if (typeof window === "undefined" || !window.location) return false;
  const url = window.location.href.toLowerCase();
  const unsupportedPatterns = [
    "chrome://",
    "chrome-extension://",
    "moz-extension://",
    "edge://",
    "about:",
    "data:",
    "file://",
  ];
  return !unsupportedPatterns.some((pattern) => url.startsWith(pattern));
}
